import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { CreateMenuDto } from './dto/create-menu.dto'
import { UpdateMenuDto } from './dto/update-menu.dto'
import { InjectRepository } from '@nestjs/typeorm'
import { Menus } from './menus.entity'
import { Repository } from 'typeorm'

@Injectable()
export class MenusService {
  constructor(@InjectRepository(Menus) private readonly menusRepository: Repository<Menus>) {}
  async create(createMenuDto: CreateMenuDto) {
    const menu = this.menusRepository.create(createMenuDto)
    return await this.menusRepository.save(menu)
  }

  async findAll() {
    return await this.menusRepository.find()
  }

  async findOne(id: number) {
    return await this.menusRepository.findOne({ where: { id } })
  }

  async update(id: number, updateMenuDto: UpdateMenuDto) {
    const menu = await this.findOne(id)
    if (menu) {
      const TempMenu = this.menusRepository.merge(menu, updateMenuDto)
      return await this.menusRepository.save(TempMenu)
    } else {
      throw new HttpException('该数据不存在', HttpStatus.NOT_FOUND)
    }
  }

  async remove(id: number) {
    const menu = await this.findOne(id)
    if (menu) {
      const res = await this.menusRepository.remove(menu)
      return `菜单名为'${res.name}'的数据已删除`
    } else {
      throw new HttpException('该数据不存在', HttpStatus.NOT_FOUND)
    }
  }
}
